<template>
  <div class="homework-management">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="作业ID">
            <el-input
                v-model="filterForm.assignmentId"
                placeholder="请输入作业ID"
                @keyup.enter="queryHomeworkDetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="queryHomeworkDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <el-button type="success" @click="addDialogVisible = true">发布作业</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
        v-model="queryDialogVisible"
        title="作业信息查询结果"
        width="50%"
        @close="handleQueryDialogClose"
    >
      <el-form :model="queryHomeworkInfo" label-width="120px">
        <el-form-item label="作业ID">
          <el-input v-model="queryHomeworkInfo.assignmentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业标题">
          <el-input v-model="queryHomeworkInfo.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业内容">
          <el-input v-model="queryHomeworkInfo.content" disabled></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-input v-model="queryHomeworkInfo.startTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="截止时间">
          <el-input v-model="queryHomeworkInfo.dueTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业状态">
          <el-input v-model="queryHomeworkInfo.state" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业附件">
          <el-button
              v-if="queryHomeworkInfo.attachment"
              type="text"
              @click="downloadAttachment(queryHomeworkInfo.attachment)"
          >下载附件</el-button>
          <span v-else>无附件</span>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 作业列表 -->
    <el-card class="homework-list-card">
      <div class="table-container">
        <el-table
            :data="homeworkList"
            stripe
            border
            @row-dblclick="handleRowClick"
            style="width: 100%;"
            max-height="500px"
        >
          <el-table-column prop="assignmentId" label="作业ID"></el-table-column>
          <el-table-column prop="title" label="作业标题"></el-table-column>
          <el-table-column prop="content" label="作业内容"></el-table-column>
          <el-table-column prop="startTime" label="开始时间"></el-table-column>
          <el-table-column prop="dueTime" label="截止时间"></el-table-column>
          <el-table-column prop="classIds" label="班级ID"></el-table-column>
          <el-table-column prop="state" label="作业状态">
            <template
                #default="scope"
            >{{ scope.row.state === '1' ? '未批改' : scope.row.state === '2' ? '已批改' : '未知' }}</template>
          </el-table-column>
          <el-table-column prop="attachment" label="作业附件">
            <template #default="scope">
              <el-button
                  v-if="scope.row.attachment"
                  type="text"
                  @click="downloadAttachment(scope.row.attachment)"
              >下载附件</el-button>
              <span v-else>无附件</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200px">
            <template #default="scope">
              <el-button
                  v-if="scope.row.state !== '2'"
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                  v-if="scope.row.state === '2'"
                  type="primary"
                  size="small"
                  @click="gotoGrading(scope.row.assignmentId)"
              >查看</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              <el-button
                  v-if="scope.row.state !== '2'"
                  type="warning"
                  size="small"
                  @click="gotoGrading(scope.row)"
              >批改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 发布作业对话框 -->
    <el-dialog v-model="addDialogVisible" title="发布作业" width="50%" @close="handleAddDialogClose">
      <el-form :model="addForm" label-width="120px" :rules="addFormRules">
        <el-form-item label="教学ID" prop="teachId">
          <el-input v-model="addForm.teachId"></el-input>
        </el-form-item>
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="作业内容" prop="content">
          <el-input v-model="addForm.content"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <div class="block">
            <el-date-picker v-model="addForm.startTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="截止时间" prop="dueTime">
          <div class="block">
            <el-date-picker v-model="addForm.dueTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="作业附件" prop="file">
          <el-upload
              ref="uploadRef"
              action="#"
              :show-file-list="false"
              :on-change="handleFileChange"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑作业对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑作业" width="50%" @close="handleEditDialogClose">
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="editFormRules">
        <el-form-item label="作业ID" prop="assignmentId">
          <el-input v-model="editForm.assignmentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="教学ID" prop="teachId">
          <el-input v-model="editForm.teachId"></el-input>
        </el-form-item>
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="作业内容" prop="content">
          <el-input v-model="editForm.content"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <div class="block">
            <el-date-picker v-model="editForm.startTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="截止时间" prop="dueTime">
          <div class="block">
            <el-date-picker v-model="editForm.dueTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="作业状态" prop="state">
          <el-select v-model="editForm.state" placeholder="请选择作业状态">
            <el-option label="未批改" value="1"></el-option>
            <el-option label="已批改" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作业附件" prop="file">
          <el-upload
              ref="editUploadRef"
              action="#"
              :show-file-list="false"
              :on-change="handleEditFileChange"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import { formatDate } from "@/utils/common";
const router = useRouter();
const route = useRoute();
// 筛选条件
const filterForm = reactive({
  assignmentId: "",
  title: "",
  content: "",
  startTime: "",
  dueTime: "",
  state: "",
  teachId: route.query.teachId || "" // 接收传递过来的教学 ID，如果没有则为空
});

// 表格数据和分页
const homeworkList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryHomeworkInfo = ref({
  assignmentId: "",
  title: "",
  content: "",
  startTime: "",
  dueTime: "",
  state: "",
  attachment: null
});

// 发布作业相关
const addDialogVisible = ref(false);
const addForm = ref({
  teachId: "",
  title: "",
  content: "",
  startTime: "",
  dueTime: "",
  file: null
});
const uploadRef = ref(null);

// 编辑作业相关
const editDialogVisible = ref(false);
const editForm = ref({
  assignmentId: "",
  teachId: "",
  title: "",
  content: "",
  startTime: "",
  dueTime: "",
  state: "",
  file: null
});
const editUploadRef = ref(null);
const editFormRef = ref(null);

//查询
const queryHomeworkDetail = async () => {
  const assignmentId = filterForm.assignmentId;
  if (!assignmentId) {
    ElMessage.warning("请输入作业ID");
    return;
  }
  try {
    const response = await axios.get(
        `/assignments/getAssignmentDetail?assignmentId=${assignmentId}`
    );
    if (response.data.flag) {
      queryHomeworkInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || "查询失败");
    }
  } catch (error) {
    console.error("查询出错:", error);
    ElMessage.error("查询时发生错误，请稍后重试");
  }
};

// 确认发布
const submitAddForm = async () => {
  const formData = new FormData();
  formData.append("teachId", addForm.value.teachId);
  formData.append("title", addForm.value.title);
  formData.append("content", addForm.value.content);
  if (addForm.value.startTime) {
    formData.append("startTime", formatDate(addForm.value.startTime));
  }
  if (addForm.value.dueTime) {
    formData.append("dueTime", formatDate(addForm.value.dueTime));
  }
  if (addForm.value.file) {
    formData.append("file", addForm.value.file);
  }
  try {
    const response = await axios.post("/assignments/uploadAssignment", formData);
    if (response.data.flag) {
      ElMessage.success("发布成功");
      addDialogVisible.value = false;

      addForm.value = {
        teachId: "",
        title: "",
        content: "",
        startTime: "",
        dueTime: "",
        file: null
      };
      uploadRef.value.clearFiles();

      fetchHomeworkList();
    } else {
      ElMessage.error("发布失败：" + response.data.message || "未知错误");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("发布失败，请稍后重试");
  }
};

// 编辑
const handleEdit = row => {
  editDialogVisible.value = true;
  editForm.value = { ...row };
};

// 提交编辑
const submitEditForm = async () => {
  await editFormRef.value.validate(async valid => {
    if (!valid) {
      return;
    }
    const formData = new FormData();
    formData.append("assignmentId", editForm.value.assignmentId);
    formData.append("teachId", editForm.value.teachId);
    formData.append("title", editForm.value.title);
    formData.append("content", editForm.value.content);
    if (editForm.value.startTime) {
      formData.append("startTime", formatDate(editForm.value.startTime));
    }
    if (editForm.value.dueTime) {
      formData.append("dueTime", formatDate(editForm.value.dueTime));
    }
    if (editForm.value.state) {
      formData.append("state", editForm.value.state);
    }
    if (editForm.value.file) {
      formData.append("file", editForm.value.file);
    }

    try {
      const response = await axios.post(
          "/assignments/updateAssignment",
          formData
      );
      if (response.data.flag) {
        ElMessage.success("作业信息更新成功！");
        editDialogVisible.value = false;
        editFormRef.value.resetFields();
        editUploadRef.value.clearFiles();
        fetchHomeworkList();
      } else {
        ElMessage.error("更新失败！");
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.assignmentId = "";
  filterForm.title = "";
  filterForm.content = "";
  filterForm.startTime = "";
  filterForm.dueTime = "";
  filterForm.state = "";
  filterForm.classIds = "";
  fetchHomeworkList();
};

// 添加表单验证规则
const addFormRules = computed(() => ({
  teachId: [{ required: true, message: "请输入教学ID", trigger: "blur" }],
  title: [{ required: true, message: "请输入作业标题", trigger: "blur" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  dueTime: [{ required: true, message: "请选择截止时间", trigger: "change" }]
}));

// 编辑表单验证规则
const editFormRules = computed(() => ({
  teachId: [{ required: true, message: "请输入教学ID", trigger: "blur" }],
  title: [{ required: true, message: "请输入作业标题", trigger: "blur" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  dueTime: [{ required: true, message: "请选择截止时间", trigger: "change" }],
  state: [{ required: true, message: "请选择作业状态", trigger: "change" }]
}));

// 生命周期钩子
onMounted(async () => {
  await fetchHomeworkList();
});

// 获取作业列表
const fetchHomeworkList = async () => {
  try {
    const params = {
      ...filterForm,
      page: currentPage.value,
      size: pageSize.value,
      teacherId:localStorage.getItem("teacherId")
    };
    console.log(params);
    const response = await axios.get("/assignments/selectAssignmentByInfos", {
      params
    });
    homeworkList.value = response.data.result || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error("获取作业列表失败", error);
    ElMessage.error("获取作业列表失败，请稍后重试");
  }
};

const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryHomeworkInfo.value = {
    assignmentId: "",
    title: "",
    content: "",
    startTime: "",
    dueTime: "",
    state: "",
    attachment: null
  };
};

// 添加对话框关闭时处理
const handleAddDialogClose = () => {
  addDialogVisible.value = false;
};

// 编辑对话框关闭时处理
const handleEditDialogClose = () => {
  editDialogVisible.value = false;
  editForm.value = {}; // 重置表单对象
  editUploadRef.value.clearFiles();
};

// 删除作业
const handleDelete = homework => {
  ElMessageBox.confirm(
      `确定要删除作业 "${homework.title}" (${homework.assignmentId}) 吗？删除后将无法恢复。`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      }
  )
      .then(async () => {
        try {
          const response = await axios.delete(
              `/assignments/deleteAssignment?assignmentId=${homework.assignmentId}`
          );
          if (response.data.flag) {
            ElMessage.success("作业删除成功");
            fetchHomeworkList();
          } else {
            ElMessage.error(response.data.message || "作业删除失败");
          }
        } catch (error) {
          console.error("删除作业失败", error);
          ElMessage.error("删除作业失败，请稍后重试");
        }
      })
      .catch(() => {
        // 取消操作
      });
};

// 双击行事件处理
const handleRowClick = row => {
  // 仅当作业状态不是已批改时才允许编辑
  if (row.state !== "2") {
    handleEdit(row);
  } else {
    ElMessage.info("已批改的作业不允许编辑");
  }
};

// 分页控制
const handleSizeChange = newSize => {
  pageSize.value = newSize;
  fetchHomeworkList();
};

const handleCurrentChange = newPage => {
  currentPage.value = newPage;
  fetchHomeworkList();
};

// 处理添加作业时文件选择
const handleFileChange = file => {
  addForm.value.file = file.raw;
};

// 处理编辑作业时文件选择
const handleEditFileChange = file => {
  editForm.value.file = file.raw;
};

// 跳转到批改作业界面
const gotoGrading = row => {
  router.push({
    name: "GradingManagement",
    query: {
      assignmentId: row.assignmentId,
      classIds: row.classIds
    }
  });
};
// 下载附件
const downloadAttachment = async attachment => {
  console.log(attachment);
  try {
    const response = await axios.put(
      `/attachments/downloadAttachmentByAttachmentId?attachmentId=${attachment}`
    );

    if (response.data.flag) {
      let fileName = 'document.docx';
      const contentDisposition = response.headers['content-disposition'];
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (fileNameMatch && fileNameMatch[1]) {
          fileName = fileNameMatch[1].replace(/['"]/g, '');
        }

    }
    // 创建下载链接
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);

      // 执行下载
      link.click();

      // 清理资源
      setTimeout(() => {
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }, 100);
    } else {
      ElMessage.error('下载失败，服务器返回错误');
    }
  } catch (error) {
    console.error("下载附件出错:", error);
    ElMessage.error("下载附件时发生错误，请稍后重试");
  }
};
</script>

<style scoped>
.homework-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.homework-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>